package sessionbeans;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.*;

import com.sun.org.apache.commons.collections.Factory;

import dtofactory.FactoryDTO;

import entities.*;
import entitiesdto.*;
import sessionbeans.AdminArticulos;

@Stateless 
public class AdminArticulosBean implements AdminArticulos {

	@PersistenceContext
	private EntityManager manager;
	private FactoryDTO dtoFactory;
	
	public AdminArticulosBean(){
		dtoFactory=FactoryDTO.getInstance();
	}
	
	public boolean ingresarNuevoArticulo(ArticuloDTO art) {
		
		if (art instanceof HogarDTO) {
			Hogar artHogar = (Hogar) dtoFactory.dtoToArt(art);
			manager.persist(artHogar);
		} else {
			if (art instanceof RopaDTO) {
				Ropa artRopa = (Ropa) dtoFactory.dtoToArt(art);
				manager.persist(artRopa);
			}
		}
		return true;		
	}

	@SuppressWarnings("unchecked")
	public List<MateriaPrimaDTO> getMateriasPrimas() {
		List<MateriaPrima> mp = manager.createQuery("select m from MateriaPrima m").getResultList();
		List<MateriaPrimaDTO> result = new ArrayList<MateriaPrimaDTO>();
		for(MateriaPrima mater : mp){
			MateriaPrimaDTO material= FactoryDTO.getInstance().mpToDto(mater);
			result.add(material);
		}
		return result;
	}

	public ArticuloDTO getArticulofromRef(String ref) {
		Articulo a = manager.find(Articulo.class, ref);
		return dtoFactory.artToDto(a);
	}

	public Articulo getArticulo(String ref) {
		return manager.find(Articulo.class, ref);
	}
}
